package com.bidevalution.service.task;

import com.bidevalution.core.Common;
import com.bidevalution.core.constant.ConfigConstant;
import com.bidevalution.core.constant.LocalPathConstant;
import com.bidevalution.core.enums.FileStatusEnum;
import com.bidevalution.core.enums.FileTypeEnum;
import com.bidevalution.core.util.HttpClientUtil;
import com.bidevalution.dao.ApiBidFileMapper;
import com.bidevalution.dao.ApiSectionEnterpriseMapper;
import com.bidevalution.model.BidFile;
import com.qtp.core.model.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @author huyiqi
 * @date 2019/11/13
 */
@Component
public class DownloadImportFile {

    private static final Logger log = LoggerFactory.getLogger(DownloadImportFile.class);

    public void beginTask() {
        log.info("======本地标文件任务开始======");
        List<BidFile> list = bidFileMapper.findNeedDownloadFile(null, ConfigConstant.MAX_ALLOW_DOWNLOAD_FAIL_TIMES);
        if(list != null) {
            log.info("======一共有"+list.size()+"个文件======");
            int i=0;
            for(BidFile bidFile:list) {
                i++;
                log.info("======正在处理第"+i+"个文件======");
                String fileId = bidFile.getFileId();
                String localFilePath;
                String downloadUrl = Common.spliceUrl(LocalPathConstant.FILE_SERVER_URL, "UploadedFile", fileId);
                Integer fileType = bidFile.getFileType();
                log.info("======第"+i+"个文件下载路径："+downloadUrl+"======");
                try {
                    //获取文件保存的路径
                    if (FileTypeEnum.TB.getType() == fileType) {
                        localFilePath = Common.splicePath(LocalPathConstant.TB_FILE_PATH, UUID.randomUUID().toString());
                        String bidEntId = UUID.randomUUID().toString();
                        bidFile.setBidEntId(bidEntId);
                        //往企业表插入数据
                        enterpriseMapper.insertWhenLocalImport(UUID.randomUUID().toString(), bidEntId);
                    } else {
                        localFilePath = Common.splicePath(LocalPathConstant.ZB_FILE_PATH, UUID.randomUUID().toString());
                    }
                    //下载并保存到本地
                    Response<String> result = HttpClientUtil.downloadFile(downloadUrl, localFilePath);
                    if(result.isSuccess()) {
                        try {
                            log.info("======准备更新数据库======");
                            bidFile.setStatus(FileStatusEnum.DOWNLOAD_SUCCESS.getStatus());
                            String filePath = result.getResult();
                            bidFile.setFileName(Common.getFileNameByPath(filePath));
                            bidFile.setFilePath(filePath);
                            bidFileMapper.update(bidFile);
                            log.info("======数据库更新完成======");
                        } catch (Exception e) {
                            log.info("======文件下载失败======");
                            addFailTime(bidFile);
                        }
                    } else {
                        bidFile.setStatus(FileStatusEnum.DOWNLOAD_FAIL.getStatus());
                        bidFileMapper.update(bidFile);
                        log.info("======文件下载失败======");
                        addFailTime(bidFile);
                    }
                } catch (Exception e) {
                    log.error("下载光盘文件出错", e);
                    addFailTime(bidFile);
                }
            }
        }
        log.info("======本地标文件任务结束======");
    }

    private void addFailTime(BidFile bidFile) {
        int failTime = bidFile.getDownloadFailTimes();
        bidFile.setDownloadFailTimes(++failTime);
        bidFileMapper.update(bidFile);
    }



    @Autowired(required = false)
    private ApiBidFileMapper bidFileMapper;

    @Autowired(required = false)
    private ApiSectionEnterpriseMapper enterpriseMapper;
}
